package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public ResultInfo login(String username, String password) {
        //根据username从数据库中查询,查不到就返回用户名不存在
        Employee employee= employeeMapper.findByName(username);
        if (employee==null) {
            return ResultInfo.error("用户名不存在");
        }
        //比对密码 (前端提交VS数据库)前端提交的密码加密之后和后端再进行比较 失败返回密码错误
        String md5Password = SecureUtil.md5(password);
        if (!StringUtils.equals(md5Password,employee.getPassword())) {
            return ResultInfo.error("密码错误");
        }
        //确定员工状态status 正常 1 禁用0
        if (employee.getStatus()== Employee.STATUS_DISABLE) {
            return ResultInfo.error("用户被禁用");
        }
        return ResultInfo.success(employee);
    }
    //根据name查询
    @Override
    public List<Employee> findByUsername(String name) {

        return employeeMapper.findByUsername(name);
    }
    //新增员工
    @Override
    public void save(Employee employee) {
        employee.setId(IdUtil.getSnowflake(1, 1).nextId());
        employee.setPassword(SecureUtil.md5("123"));
        employee.setStatus(Employee.STATUS_ENABLE);
      /*  employee.setCreateUser(1L);
        employee.setCreateTime(new Date());
        employee.setUpdateTime(new Date());

        employee.setCreateUser(1L);
        employee.setUpdateUser(1L);*/

        employeeMapper.save(employee);

    }
//修改查询
    @Override
    public Employee findById(Long id) {

        return employeeMapper.findById(id);
    }
//修改
    @Override
    public void update(Employee employee) {
      /*  employee.setUpdateTime(new Date());
        employee.setUpdateUser(1L);*/
        employeeMapper.update(employee);
    }
}
